<template>
  <div class="main-container">
    <!-- 上半部分：甘特图 -->
    <div class="gantt-section">
      <div class="container">
        <!-- 搜索区域 -->
        <div class="search-container">
          <button class="today-button" @click="scrollToToday">
            <i class="fas fa-clock"></i> 今天
          </button>
          <div class="search-box">
            <i class="fas fa-search"></i>
            <input 
              type="text" 
              v-model="searchQuery" 
              placeholder="搜索订单号或模具号..." 
              @input="handleSearch"
            >
          </div>
          <div class="search-result">
            找到 {{ filteredOrders.length }} 个匹配结果，显示 {{ filteredMachines.length }} 台相关压机
          </div>
        </div>
        
        <div class="gantt-container">
          <div class="header-container">
            <div class="machine-header">
              <div class="header-cell">设备名称</div>
            </div>
            <div class="date-header-container" ref="dateHeader" @mousedown="startDragging" @mousemove="handleDrag" @mouseup="stopDragging" @mouseleave="stopDragging">
              <div class="date-header" ref="dateHeaderContent">
                <div 
                  v-for="(date, index) in dateHeaders" 
                  :key="index"
                  :class="['date-cell', { 
                    'today': isToday(date), 
                    'weekend': isWeekend(date) 
                  }]"
                >
                  {{ formatDateHeader(date) }}
                </div>
              </div>
            </div>
          </div>

          <div class="body-container" ref="scrollContainer" @mousemove="handleVerticalDrag" @mouseup="stopDraggingOrder" @mouseleave="stopDraggingOrder">
            <div class="scroll-indicator" v-if="showScrollHint">
              <i class="fas fa-arrows-alt-h"></i> 点击并拖动日期表头滚动
            </div>
            
            <div class="machine-names">
              <div 
                v-for="machine in filteredMachines" 
                :key="machine.id"
                class="machine-cell"
                :class="{ 'machine-hover': machine.id === hoveredMachineId }"
              >
                <i class="fas fa-industry"></i> {{ machine.name }}
              </div>
            </div>
            
            <div class="gantt-body">
              <div 
                v-for="machine in filteredMachines" 
                :key="'row-'+machine.id"
                class="gantt-row"
                :class="{ 'row-hover': machine.id === hoveredMachineId }"
              >
                <div 
                  v-for="(date, dateIndex) in dateHeaders" 
                  :key="'cell-'+dateIndex"
                  :class="['gantt-cell', { 'weekend': isWeekend(date) }]"
                >
                  <div 
                    v-for="order in getFilteredOrdersForCell(machine.id, date)" 
                    :key="order.id"
                    class="order-block"
                    :style="getOrderBlockStyle(order, date)"
                    @mouseenter="showTooltip($event, order)"
                    @mouseleave="hideTooltip"
                    @mousedown="startDraggingOrder($event, order, machine.id)"
                    :class="{ 'dragging': isDraggingOrder && draggedOrder.id === order.id }"
                  >
                    <!-- 订单基础信息 -->
                    <div class="order-info">
                      <span class="order-id">{{ order.id }}</span>
                      <span class="separator">|</span>
                      <span class="mold-id">{{ order.mold_id }}</span>
                    </div>
                    <!-- 进度条容器 -->
                    <div class="progress-container">
                      <div 
                        class="progress-bar" 
                        :style="{ 
                          width: `${order.completionRate}%`,
                          backgroundColor: getProgressColor(order.completionRate)
                        }"
                      ></div>
                    </div>
                    <!-- 进度文本 -->
                    <div class="progress-text">
                      {{ Math.round(order.completionRate) }}%
                    </div>
                  </div>
                  <div v-if="isToday(date)" class="today-marker"></div>
                  <div 
                    v-if="getFilteredOrdersForCell(machine.id, date).length === 0" 
                    class="empty-cell"
                  >
                    空闲
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div v-if="tooltip.visible" class="tooltip" :style="tooltipStyle">
          <h4>{{ tooltip.order.id }}</h4>
          <p>模具号: {{ tooltip.order.mold_id || '未知' }}</p>
          <p><span class="status-indicator" :class="'status-' + tooltip.order.status"></span> 状态: {{ getStatusText(tooltip.order.status) }}</p>
          <p><i class="fas fa-industry"></i> 设备: {{ tooltip.order.machine }}</p>
          <p><i class="fas fa-play-circle"></i> 开始: {{ formatDate(tooltip.order.startDate) }}</p>
          <p><i class="fas fa-flag-checkered"></i> 结束: {{ formatDate(tooltip.order.endDate) }}</p>
          <p><i class="fas fa-hourglass-half"></i> 时长: {{ tooltip.order.duration }}天</p>
          <p><i class="fas fa-box"></i> 产品: {{ tooltip.order.product }}</p>
          <p><i class="fas fa-box"></i> 日排产量: {{ tooltip.order.per_day }}</p>
          <!-- 新增进度信息 -->
          <p><i class="fas fa-chart-line"></i> 完成进度: {{ Math.round(tooltip.order.completionRate) }}% ({{ tooltip.order.completedQuantity }}/{{ tooltip.order.quantity }}件)</p>
        </div>
        
        <!-- 拖拽提示 -->
        <div v-if="isDraggingOrder" class="drag-hint">
          <i class="fas fa-info-circle"></i> 拖动调整排产日期和压机，松开鼠标确认
        </div>
        
        <!-- 冲突提示 -->
        <div v-if="showConflictWarning" class="conflict-warning">
          <i class="fas fa-exclamation-triangle"></i> 警告：该时间段与其他订单冲突！
        </div>
      </div>
    </div>

    <!-- 下半部分：未排产订单表单 -->
    <div class="unscheduled-section">
      <div class="section-header">
        <h2>未排产订单</h2>
      </div>
      
      <div class="table-container">
        <!-- 表头（冻结） -->
        <div class="table-header">
          <div class="table-row">
            <div class="table-cell index-column">序号</div>
            <div class="table-cell order-id-column">订单号</div>
            <div class="table-cell product-column">产品</div>
            <div class="table-cell mold-column">模具</div>
            <div class="table-cell quantity-column">数量</div>
            <div class="table-cell deadline-column">交期</div>
          </div>
        </div>
        
        <!-- 表格内容（可滚动） -->
        <div class="table-body">
          <div 
            class="table-row" 
            v-for="(order, index) in unscheduledOrders" 
            :key="order.id"
            :class="{ 'row-hover': index === hoveredRowIndex }"
            @mouseenter="hoveredRowIndex = index"
            @mouseleave="hoveredRowIndex = -1"
          >
            <div class="table-cell index-column">{{ index + 1 }}</div>
            <div class="table-cell order-id-column">{{ order.id }}</div>
            <div class="table-cell product-column">{{ order.product }}</div>
            <div class="table-cell mold-column">{{ order.mold_id || '未知' }}</div>
            <div class="table-cell quantity-column">{{ order.quantity }}</div>
            <div class="table-cell deadline-column">{{ order.deadline}}</div>
          </div>
          
          <!-- 空状态 -->
          <div v-if="unscheduledOrders.length === 0" class="empty-state">
            <i class="fas fa-box-open"></i>
            <p>当前没有未排产的订单</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
export default {
  data() {
    // 生成6台压机
    const machines_ = ['B-01', 'B-02', 'B-03', 'B-04', 'Q-01', 'Q-02']
    const machines = []
    const order_list = []
    for(let i = 0;i<machines_.length;i++){
      let a = {
        id:i+1,
        name:machines_[i]
      }
      machines.push(a)
    }

    // 生成日期表头（当前日期前后各30天）
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const dateHeaders = Array.from({ length: 61 }, (_, i) => {
      const date = new Date(today);
      date.setDate(today.getDate() - 30 + i);
      return date;
    });

    // 生成未排产订单数据
    const unscheduledOrders = [
      {
        id: 'ORD-9001',
        product: '产品A-100',
        mold_id: 'M-1001',
        quantity: 5000,
        deadline: new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000) // 7天后
      },
      {
        id: 'ORD-9002',
        product: '产品B-200',
        mold_id: 'M-2003',
        quantity: 3000,
        deadline: new Date(today.getTime() + 10 * 24 * 60 * 60 * 1000) // 10天后
      },
      {
        id: 'ORD-9003',
        product: '产品C-300',
        mold_id: 'M-3005',
        quantity: 8000,
        deadline: new Date(today.getTime() + 14 * 24 * 60 * 60 * 1000) // 14天后
      },
      {
        id: 'ORD-9004',
        product: '产品D-400',
        mold_id: 'M-4002',
        quantity: 2000,
        deadline: new Date(today.getTime() + 5 * 24 * 60 * 60 * 1000) // 5天后
      },
      {
        id: 'ORD-9005',
        product: '产品E-500',
        mold_id: 'M-5001',
        quantity: 6000,
        deadline: new Date(today.getTime() + 20 * 24 * 60 * 60 * 1000) // 20天后
      },
      {
        id: 'ORD-9006',
        product: '产品F-600',
        mold_id: 'M-6004',
        quantity: 4500,
        deadline: new Date(today.getTime() + 12 * 24 * 60 * 60 * 1000) // 12天后
      },
      {
        id: 'ORD-9007',
        product: '产品G-700',
        mold_id: 'M-7002',
        quantity: 7000,
        deadline: new Date(today.getTime() + 8 * 24 * 60 * 60 * 1000) // 8天后
      }
    ];

    return {
      machines,
      dateHeaders,
      orders: [], // 原始订单数据
      filteredOrders: [], // 搜索过滤后的订单
      filteredMachines: [], // 过滤后的压机列表
      unscheduledOrders: unscheduledOrders, // 未排产订单
      cellWidth: 100,
      rowHeight: 70, // 行高，用于垂直拖动计算
      tooltip: {
        visible: false,
        order: null,
        x: 0,
        y: 0
      },
      showScrollHint: true,
      // 拖动相关状态
      isDragging: false,
      lastX: 0,
      scrollLeft: 0,
      // 订单拖动相关状态
      isDraggingOrder: false,
      draggedOrder: null,
      dragStartX: 0,
      dragStartY: 0,
      originalStartDate: null,
      originalMachineId: null,
      dragOffsetX: 0,
      showConflictWarning: false,
      hoveredMachineId: null,
      hoveredRowIndex: -1, // 未排产订单表格行悬停索引
      // 无限滚动相关状态
      scrollThreshold: 300,
      isLoading: false,
      // 搜索相关状态
      searchQuery: ''
    };
  },
  computed: {
    dateRangeText() {
      if (this.dateHeaders.length === 0) return '';
      const start = this.formatDate(this.dateHeaders[0]);
      const end = this.formatDate(this.dateHeaders[this.dateHeaders.length - 1]);
      return `${start} 至 ${end}`;
    },
    tooltipStyle() {
      return {
        left: `${this.tooltip.x}px`,
        top: `${this.tooltip.y}px`
      };
    }
  },
  mounted() {
    this.syncScroll();
    this.get_data_orders(); // 加载时获取数据
    // 5秒后隐藏滚动提示
    setTimeout(() => {
      this.showScrollHint = false;
    }, 5000);
    
    // 设置日期表头的样式，使其可以被拖动
    this.$refs.dateHeader.style.cursor = 'grab';
    
    // 添加滚动事件监听，实现无限滚动
    this.$refs.dateHeader.addEventListener('scroll', this.handleScroll);
    // this.scrollToToday();
    
    this.get_no_plan();
  },
  beforeDestroy() {
    // 移除滚动事件监听
    this.$refs.dateHeader.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    get_no_plan(){
      this.unscheduledOrders = []
      this.http.get('api/material_plan_xie/get_no_plan_order',
                          {}).then((reslut) => {
                            console.log("reslut[0]",reslut)
                            console.log("reslut[0]")
                            for(let i=0;i<reslut.length;i++){
                              if(reslut[i]["mold_id"] == ""){
                                this.unscheduledOrders.push(
                                  {
                                    id: reslut[i]["schedule_id"],
                                    product: reslut[i]["top_id"],
                                    mold_id: reslut[i]["mold_id"],
                                    quantity: reslut[i]["product_qty"],
                                    deadline: reslut[i]["date_first_batch"].split(" ")[0],                            
                                  },
                                )
                              }                              
                            }                            
                        }).catch((error) => {
                            console.log("失败",error)
                            // return "未更新"
                        });
    },
    scrollToToday() {
     const today = new Date();
     today.setHours(0, 0, 0, 0);
     
     // 查找当天日期在dateHeaders中的索引
     const index = this.dateHeaders.findIndex(date => 
       date.toDateString() === today.toDateString()
     );

     if (index === -1) return;

     // 计算滚动位置
     const cellWidth = this.cellWidth;
     const scrollPosition = index * cellWidth;
     
     // 执行滚动
     this.$refs.dateHeader.scrollLeft = scrollPosition;
     this.$refs.scrollContainer.scrollLeft = scrollPosition;

     // 可选：高亮今天单元格
     this.highlightTodayCell(index);
   },

   highlightTodayCell(index) {
     // 移除之前高亮
     document.querySelectorAll('.date-cell').forEach(cell => {
       cell.classList.remove('highlighted');
     });

     // 添加新高亮
     const cell = this.$refs.dateHeaderContent.children[index];
     if (cell) {
       cell.classList.add('highlighted');
     }
   },
    get_data_orders(){
      console.log("开始加载订单数据...")
      this.http.get('api/material_plan_xie/get_db_proinfo', {}).then((reslut) => {
          console.log("接口返回数据：", reslut);
          this.order_list = reslut
          console.log("SSS",this.order_list)
          if (!reslut || !reslut.length) {
          console.log("接口返回空数据");
          return;
          }

          this.orders = [];
          const today = new Date();
          today.setHours(0, 0, 0, 0);

          reslut.forEach(item => {
            // 1. 处理压机ID
            const machineId = item.yx_device;
            if (!machineId || isNaN(machineId) || machineId < 1 || machineId > 6) {
                console.log(`跳过无效压机ID的数据：${machineId}`);
                return;
            }

            // 2. 安全处理日期
            const startDateStr = item.yx_startdate || '';
            const startDate = this.parseDate(startDateStr);
            if (!startDate) {
                console.log(`跳过无效开始日期的数据：${startDateStr}`);
                return;
            }

            // 3. 安全处理持续天数
            const duration = parseInt(item.yx_dunring || '1', 10);
            if (isNaN(duration) || duration < 1) {
                console.log(`无效持续天数，默认设为1天：${item.yx_dunring}`);
            }

            // 4. 计算结束日期
            const endDate = new Date(startDate);
            endDate.setDate(startDate.getDate() + duration - 1);

            // 5. 确定订单状态
            let status = 'pending';
            if (endDate < today) {
                status = 'completed';
            } else if (startDate <= today && endDate >= today) {
                status = 'active';
            }
            var color = "";
            var textColor = "";
            // 6. 生成随机颜色和文本颜色
            if(item.color == ""){
              console.log("wowowo  wow owo   wo   wowowo，没有颜色")
              color = this.generateRandomColor();
              this.http.get('api/material_plan_xie/update_color_yaji', {order:item.schedule_id,color_:color}).then((reslut) => {
                  console.log(reslut)                  
                }).catch((error) => {
                console.error("接口请求失败：", error);
              });
            }else{
              color = item.color;
            }
            textColor = this.getContrastColor(color);
            
            // 7. 计算完成进度（新增）
            const totalQuantity = parseInt(item.product_qty || '0', 10);
            const completedQuantity = this.calculateCompletedQuantity(item, today, startDate, endDate);
            const completionRate = totalQuantity > 0 ? (completedQuantity / totalQuantity) * 100 : 0;
            
            // 8. 构建订单对象，包含模具号和进度信息
            const order = {
                id: item.schedule_id || `ORD-${Date.now()}`,
                mold_id: item.mold_id || '未知', // 模具号
                machineId: machineId,
                startDate: startDate,
                endDate: endDate,
                duration: duration,
                status: status,
                product: item.top_id || '未知产品',
                per_day: item.yx_per_in || '0',
                color: color,
                textColor: textColor,
                quantity: totalQuantity, // 总数量（新增）
                completedQuantity: completedQuantity, // 已完成数量（新增）
                completionRate: completionRate // 完成率（新增）
            };
            console.log("颜色：",item.schedule_id,color,textColor)

            this.orders.push(order);
          });

          // 初始时显示所有订单和压机
          this.filteredOrders = [...this.orders];
          this.filteredMachines = [...this.machines];
          console.log("订单数据生成完成，共", this.orders.length, "条");
        }).catch((error) => {
            console.error("接口请求失败：", error);
        });
      },

    // 计算已完成数量（新增方法）
    calculateCompletedQuantity(item, today, startDate, endDate) {
      // 实际应用中应该从接口获取真实的已完成数量
      // 这里使用模拟数据，根据订单状态和时间计算
      const totalQuantity = parseInt(item.product_qty || '0', 10);
      
      // 已完成订单默认为100%
      if (endDate < today) {
        return totalQuantity;
      }
      
      // 未开始订单默认为0%
      if (startDate > today) {
        return 0;
      }
      
      // 进行中的订单根据时间进度估算
      const totalDays = (endDate - startDate) / (24 * 60 * 60 * 1000) + 1;
      const elapsedDays = (today - startDate) / (24 * 60 * 60 * 1000) + 1;
      const progressRatio = Math.min(elapsedDays / totalDays, 1);
      
      // 添加一些随机波动使数据更真实
      const randomFactor = 0.9 + Math.random() * 0.2; // 0.9-1.1之间的随机因子
      const estimatedCompleted = Math.round(totalQuantity * progressRatio * randomFactor);
      
      return Math.min(estimatedCompleted, totalQuantity);
    },

    // 获取进度条颜色（新增方法）
    getProgressColor(rate) {
      if (rate >= 100) return '#2ecc71'; // 完成 - 绿色
      if (rate >= 70) return '#3498db'; // 接近完成 - 蓝色
      if (rate >= 30) return '#f39c12'; // 进行中 - 橙色
      return '#e74c3c'; // 刚开始 - 红色
    },

    processOrderData(reslut) {
      console.log("处理订单数据：", reslut);
      if (!reslut || !reslut.length) {
        console.log("订单数据为空");
        return;
      }

      this.orders = [];
      const today = new Date();
      today.setHours(0, 0, 0, 0);

      reslut.forEach(item => {
        // 1. 处理压机ID
        const machineId = parseInt(item.yx_device);
        if (!machineId || isNaN(machineId) || machineId < 1 || machineId > 6) {
          console.log(`跳过无效压机ID的数据：${item.yx_device}`);
          return;
        }

        // 2. 安全处理日期
        const startDateStr = item.yx_startdate || '';
        const startDate = this.parseDate(startDateStr);
        if (!startDate) {
          console.log(`跳过无效开始日期的数据：${startDateStr}`);
          return;
        }

        // 3. 安全处理持续天数
        const duration = parseInt(item.yx_dunring || '1', 10);
        if (isNaN(duration) || duration < 1) {
          console.log(`无效持续天数，默认设为1天：${item.yx_dunring}`);
        }

        // 4. 计算结束日期
        const endDate = new Date(startDate);
        endDate.setDate(startDate.getDate() + duration - 1);

        // 5. 确定订单状态
        let status = 'pending';
        if (endDate < today) {
          status = 'completed';
        } else if (startDate <= today && endDate >= today) {
          status = 'active';
        }

        // 6. 生成随机颜色和文本颜色
        const color = this.generateRandomColor();
        const textColor = this.getContrastColor(color);

        // 7. 计算完成进度
        const totalQuantity = parseInt(item.product_qty || '0', 10);
        const completedQuantity = this.calculateCompletedQuantity(item, today, startDate, endDate);
        const completionRate = totalQuantity > 0 ? (completedQuantity / totalQuantity) * 100 : 0;

        // 8. 构建订单对象，包含模具号和进度信息
        const order = {
          id: item.schedule_id || `ORD-${Date.now()}`,
          mold_id: item.mold_id || '未知', // 模具号
          machineId: machineId,
          startDate: startDate,
          endDate: endDate,
          duration: duration,
          status: status,
          product: item.top_id || '未知产品',
          color: color,
          textColor: textColor,
          quantity: totalQuantity,
          completedQuantity: completedQuantity,
          completionRate: completionRate
        };

        this.orders.push(order);
      });

      // 初始时显示所有订单和压机
      this.filteredOrders = [...this.orders];
      this.filteredMachines = [...this.machines];
      console.log("订单数据生成完成，共", this.orders.length, "条");
    },

    // 处理搜索：根据订单号或模具号过滤，只显示相关的订单和压机
    handleSearch() {
      if (!this.searchQuery.trim()) {
        // 如果搜索为空，显示所有订单和压机
        this.filteredOrders = [...this.orders];
        this.filteredMachines = [...this.machines];
        return;
      }
      
      const query = this.searchQuery.trim().toLowerCase();
      
      // 模糊搜索：包含关键词的订单
      this.filteredOrders = this.orders.filter(order => 
        order.id.toLowerCase().includes(query) || 
        (order.mold_id && order.mold_id.toLowerCase().includes(query))
      );
      
      // 获取这些订单涉及的所有压机ID
      const machineIds = [...new Set(this.filteredOrders.map(order => order.machineId))];
      
      // 只显示涉及的压机
      this.filteredMachines = this.machines.filter(machine => 
        machineIds.includes(machine.id)
      );
    },

    // 开始拖动订单
    startDraggingOrder(e, order, machineId) {
      e.stopPropagation(); // 防止触发日期表头的拖动
      
      this.isDraggingOrder = true;
      this.draggedOrder = { ...order }; // 复制订单对象，避免直接修改原对象
      this.originalStartDate = new Date(order.startDate); // 保存原始开始日期
      this.originalMachineId = machineId; // 保存原始压机ID
      this.dragStartX = e.clientX;
      this.dragStartY = e.clientY;
      this.showConflictWarning = false;
      this.hoveredMachineId = null;
      
      // 计算鼠标在订单块内的偏移量
      const orderElement = e.currentTarget;
      const rect = orderElement.getBoundingClientRect();
      this.dragOffsetX = e.clientX - rect.left;
    },
    
    // 处理垂直拖动（跨压机）
    handleVerticalDrag(e) {
      if (!this.isDraggingOrder || !this.draggedOrder) return;
      
      // 首先处理水平拖动（日期调整）
      const x = e.clientX;
      const deltaX = x - this.dragStartX;
      const daysDragged = Math.round(deltaX / this.cellWidth);
      
      // 处理垂直拖动（压机调整）
      const y = e.clientY;
      const deltaY = y - this.dragStartY;
      const rowsDragged = Math.round(deltaY / this.rowHeight);
      
      // 计算新的开始日期
      const newStartDate = new Date(this.originalStartDate);
      newStartDate.setDate(this.originalStartDate.getDate() + daysDragged);
      
      // 计算新的结束日期
      const newEndDate = new Date(newStartDate);
      newEndDate.setDate(newStartDate.getDate() + this.draggedOrder.duration - 1);
      
      // 计算目标压机ID
      const originalIndex = this.filteredMachines.findIndex(m => m.id === this.originalMachineId);
      let targetIndex = originalIndex + rowsDragged;
      
      // 确保目标索引在有效范围内
      if (targetIndex < 0) targetIndex = 0;
      if (targetIndex >= this.filteredMachines.length) targetIndex = this.filteredMachines.length - 1;
      
      // 获取目标压机ID
      const targetMachineId = this.filteredMachines[targetIndex].id;
      this.hoveredMachineId = targetMachineId;
      
      // 检查是否与其他订单冲突
      const hasConflict = this.checkOrderConflict(
        targetMachineId, 
        newStartDate, 
        newEndDate, 
        this.draggedOrder.id
      );
      
      this.showConflictWarning = hasConflict;
      
      // 更新拖动中的订单信息
      const orderIndex = this.orders.findIndex(o => o.id === this.draggedOrder.id);
      if (orderIndex !== -1) {
        // 更新订单的开始和结束日期
        this.orders[orderIndex].startDate = newStartDate;
        this.orders[orderIndex].endDate = newEndDate;
        // 更新订单的压机ID
        this.orders[orderIndex].machineId = targetMachineId;
        
        // 更新订单状态（根据新日期）
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        if (newEndDate < today) {
          this.orders[orderIndex].status = 'completed';
        } else if (newStartDate <= today && newEndDate >= today) {
          this.orders[orderIndex].status = 'active';
        } else {
          this.orders[orderIndex].status = 'pending';
        }
        
        // 更新进度（如果订单时间变化）
        const totalQuantity = this.orders[orderIndex].quantity;
        const completedQuantity = this.calculateCompletedQuantity(
          this.order_list.find(item => item.schedule_id === this.draggedOrder.id) || {}, 
          today, 
          newStartDate, 
          newEndDate
        );
        this.orders[orderIndex].completedQuantity = completedQuantity;
        this.orders[orderIndex].completionRate = totalQuantity > 0 ? (completedQuantity / totalQuantity) * 100 : 0;
        
        // 同步更新过滤后的订单列表
        this.filteredOrders = [...this.orders];
      }
    },
    
    // 停止拖动订单
    stopDraggingOrder(e) {
      if (!this.isDraggingOrder || !this.draggedOrder) {
        this.isDraggingOrder = false;
        this.hoveredMachineId = null;
        return;
      }
      
      // 获取最终的目标压机ID
      let targetMachineId = this.hoveredMachineId || this.originalMachineId;
      
      // 找到最终的日期偏移
      const x = e.clientX || this.dragStartX;
      const deltaX = x - this.dragStartX;
      const daysDragged = Math.round(deltaX / this.cellWidth);
      
      // 计算最终的开始和结束日期
      const finalStartDate = new Date(this.originalStartDate);
      finalStartDate.setDate(this.originalStartDate.getDate() + daysDragged);
      
      const finalEndDate = new Date(finalStartDate);
      finalEndDate.setDate(finalStartDate.getDate() + this.draggedOrder.duration - 1);
      
      // 检查是否有冲突
      const hasConflict = this.checkOrderConflict(
        targetMachineId, 
        finalStartDate, 
        finalEndDate, 
        this.draggedOrder.id
      );
      
      if (hasConflict) {
        // 如果有冲突，恢复原始数据
        const orderIndex = this.orders.findIndex(o => o.id === this.draggedOrder.id);
        if (orderIndex !== -1) {
          this.orders[orderIndex].startDate = new Date(this.originalStartDate);
          this.orders[orderIndex].endDate = new Date(this.originalStartDate);
          this.orders[orderIndex].endDate.setDate(
            this.originalStartDate.getDate() + this.draggedOrder.duration - 1
          );
          this.orders[orderIndex].machineId = this.originalMachineId;
          this.filteredOrders = [...this.orders];
        }
        
        // 显示冲突提示信息
        alert('无法排产：该时间段与其他订单冲突！');
      } else {
        // 没有冲突，保存排产变更
        const updatedOrder = this.orders.find(o => o.id === this.draggedOrder.id);
        if (updatedOrder) {
          // 更新订单信息
          updatedOrder.startDate = finalStartDate;
          updatedOrder.endDate = finalEndDate;
          updatedOrder.machineId = targetMachineId;
          
          // 更新进度信息
          const today = new Date();
          today.setHours(0, 0, 0, 0);
          const totalQuantity = updatedOrder.quantity;
          const completedQuantity = this.calculateCompletedQuantity(
            this.order_list.find(item => item.schedule_id === updatedOrder.id) || {}, 
            today, 
            finalStartDate, 
            finalEndDate
          );
          updatedOrder.completedQuantity = completedQuantity;
          updatedOrder.completionRate = totalQuantity > 0 ? (completedQuantity / totalQuantity) * 100 : 0;
          
          console.log(`订单 ${updatedOrder.id} 已调整:`, {
            原压机: this.machines.find(m => m.id === this.originalMachineId)?.name,
            新压机: this.machines.find(m => m.id === targetMachineId)?.name,
            原开始日期: this.formatDate(this.originalStartDate),
            新开始日期: this.formatDate(updatedOrder.startDate),
            新结束日期: this.formatDate(updatedOrder.endDate),
            进度: `${Math.round(updatedOrder.completionRate)}%`
          });
          var original_date = this.formatDate(this.originalStartDate)
          var current_date = this.formatDate(updatedOrder.startDate)
          var original_device = this.machines.find(m => m.id === this.originalMachineId)?.id
          var current_device = this.machines.find(m => m.id === targetMachineId)?.id


          if(original_date != current_date || original_device != current_device){
            for(let i=0;i<this.order_list.length;i++){
              if(this.order_list[i]["schedule_id"] == updatedOrder.id){
                console.log("2222",this.order_list[i])
                console.log("yx_startdate",this.order_list[i]["yx_startdate"])
                const yx_startdate_ = new Date(this.order_list[i]["yx_startdate"]);                
                this.order_list[i]["yx_startdate"] = this.formatDate(updatedOrder.startDate)
                console.log("yx_startdate1",yx_startdate_)
                
                var qlm_startdate_ = new Date(current_date);
                console.log("yx_startdate hou",current_date)
                qlm_startdate_.setDate(qlm_startdate_.getDate());
                console.log("qlm_startdate_",qlm_startdate_,qlm_startdate_.toISOString().split('T')[0])
                this.order_list[i]["qlm_startdate"] = qlm_startdate_.toISOString().split('T')[0]
                
                var qp_startdate_ = new Date(current_date);
                qp_startdate_.setDate(qp_startdate_.getDate()-2);
                console.log("qp_startdate_",qp_startdate_,qp_startdate_.toISOString().split('T')[0])
                this.order_list[i]["qp_startdate"] = qp_startdate_.toISOString().split('T')[0]
                
                var yl_startdate_ = new Date(current_date);
                yl_startdate_.setDate(yl_startdate_.getDate()-5);
                console.log("yl_startdate_",yl_startdate_,yl_startdate_.toISOString().split('T')[0])
                this.order_list[i]["yl_startdate"] = yl_startdate_.toISOString().split('T')[0]
                
                var sj_startdate_ = new Date(current_date);
                sj_startdate_.setDate(sj_startdate_.getDate()+2);
                console.log("sj_startdate_",sj_startdate_,sj_startdate_.toISOString().split('T')[0])
                this.order_list[i]["sj_startdate"] = sj_startdate_.toISOString().split('T')[0]

                console.log("hou",this.order_list)  
                this.order_list[i]["yx_device"] = current_device


                let in_db_data = {
                  schedule_id : this.order_list[i]["schedule_id"],
                  device_type : this.order_list[i]["device_type"],
                  yl_startdate : this.order_list[i]["yl_startdate"],
                  yl_dunring : this.order_list[i]["yl_dunring"],
                  yl_per_in : this.order_list[i]["yl_per_in"],
                  // yl_stopdate : this.editingOrder["id"],
                  qp_startdate : this.order_list[i]["qp_startdate"],
                  qp_dunring : this.order_list[i]["qp_dunring"],
                  qp_per_in : this.order_list[i]["qp_per_in"],
                  // qp_stopdate : this.editingOrder["id"],
                  qlm_startdate : this.order_list[i]["qlm_startdate"],
                  qlm_dunring : this.order_list[i]["qlm_dunring"],
                  qlm_per_in: this.order_list[i]["qlm_per_in"],
                  // qlm_stopdate : this.editingOrder["id"],
                  yx_startdate : this.order_list[i]["yx_startdate"],
                  yx_dunring : this.order_list[i]["yx_dunring"],
                  yx_per_in : this.order_list[i]["yx_per_in"],
                  // 新增：保存压机选择 this.editingOrder["processes"]["pressing"]["pressMachine"]  //ceshibaocun 
                  yx_device : this.order_list[i]["yx_device"],
                  // yx_stopdate : this.editingOrder["id"],
                  sj_startdate : this.order_list[i]["sj_startdate"],
                  sj_dunring : this.order_list[i]["sj_dunring"],
                  sj_per_in : this.order_list[i]["sj_per_in"],
                  db_type : "保存",   
                }
                let jsonString_mes_data = JSON.stringify(in_db_data)
                console.log("jsonString_mes_data",jsonString_mes_data)
                this.http.get('api/material_plan_xie/get_db_order_plan',
                                  {editingOrder_data:jsonString_mes_data}).then((reslut) => {
                                    console.log(reslut)
                                    console.log("reslut[0]")                          
                                    if(reslut == "更新成功（检测到冲突并更新）"){
                                      ElMessage.success("压机排产更新成功")
                                    }
                                }).catch((error) => {
                                    console.log("失败",error)
                                    // return "未更新"
                                });

                }
            }
          }else{
            console.log("没有变化")
          }
          
          // 这里可以添加保存到服务器的代码
          // this.saveOrderSchedule(updatedOrder);
          console.log("最后",this.order_list)
        }
      }
      
      // 重置拖动状态
      this.isDraggingOrder = false;
      this.draggedOrder = null;
      this.showConflictWarning = false;
      this.hoveredMachineId = null;
    },
    
    // 检查订单冲突
    checkOrderConflict(machineId, startDate, endDate, currentOrderId) {
      // 检查同一台压机上的其他订单是否与当前订单时间重叠
      return this.orders.some(order => {
        // 排除当前订单自身
        if (order.id === currentOrderId) return false;
        
        // 只检查同一台压机
        if (order.machineId !== machineId) return false;
        
        // 检查日期范围是否重叠
        return !(
          endDate < order.startDate || 
          startDate > order.endDate
        );
      });
    },

    // 处理滚动事件，实现无限滚动
    handleScroll() {
      const { scrollLeft, scrollWidth, clientWidth } = this.$refs.dateHeader;
      if (scrollLeft < this.scrollThreshold && !this.isLoading) {
        this.loadMoreDates('left');
      }
      if (scrollLeft + clientWidth > scrollWidth - this.scrollThreshold && !this.isLoading) {
        this.loadMoreDates('right');
      }
    },

    // 加载更多日期
    loadMoreDates(direction) {
      this.isLoading = true;
      setTimeout(() => {
        const currentStartDate = this.dateHeaders[0];
        const currentEndDate = this.dateHeaders[this.dateHeaders.length - 1];
        const newDates = [];
        
        if (direction === 'left') {
          for (let i = 1; i <= 30; i++) {
            const newDate = new Date(currentStartDate);
            newDate.setDate(currentStartDate.getDate() - i);
            newDates.unshift(newDate);
          }
          const scrollOffset = newDates.length * this.cellWidth;
          this.$refs.dateHeader.scrollLeft += scrollOffset;
          this.$refs.scrollContainer.scrollLeft += scrollOffset;
          this.dateHeaders = [...newDates, ...this.dateHeaders];
        } else {
          for (let i = 1; i <= 30; i++) {
            const newDate = new Date(currentEndDate);
            newDate.setDate(currentEndDate.getDate() + i);
            newDates.push(newDate);
          }
          this.dateHeaders = [...this.dateHeaders, ...newDates];
        }
        this.isLoading = false;
      }, 300);
    },

    // 安全解析日期
    parseDate(dateStr) {
        if (typeof dateStr !== 'string' || !dateStr.trim()) {
            return null;
        }
        const date = new Date(dateStr);
        return isNaN(date.getTime()) ? null : date;
    },

    // 生成随机颜色
    generateRandomColor() {
      const letters = '0123456789ABCDEF';
      let color = '#';
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    },

    // 计算与背景色对比明显的文本颜色
    getContrastColor(hexColor) {
      hexColor = hexColor.replace('#', '');
      const r = parseInt(hexColor.substring(0, 2), 16);
      const g = parseInt(hexColor.substring(2, 4), 16);
      const b = parseInt(hexColor.substring(4, 6), 16);
      const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
      return luminance > 0.5 ? '#000000' : '#FFFFFF';
    },

    // 处理日期表头拖动
    handleDrag(e) {
      if (!this.isDragging) return;
      e.preventDefault();
      const x = e.pageX;
      const walk = (x - this.lastX) * 1.5;
      this.$refs.dateHeader.scrollLeft = this.scrollLeft - walk;
      this.$refs.scrollContainer.scrollLeft = this.scrollLeft - walk;
    },

    // 开始拖动日期表头
    startDragging(e) {
      // 如果正在拖动订单，不处理表头拖动
      if (this.isDraggingOrder) return;
      
      this.isDragging = true;
      this.lastX = e.pageX;
      this.scrollLeft = this.$refs.dateHeader.scrollLeft;
      this.$refs.dateHeader.style.cursor = 'grabbing';
      this.$refs.dateHeader.style.userSelect = 'none';
    },

    // 停止拖动日期表头
    stopDragging() {
      this.isDragging = false;
      this.$refs.dateHeader.style.cursor = 'grab';
      this.$refs.dateHeader.style.userSelect = 'auto';
    },

    // 同步滚动
    syncScroll() {
      const header = this.$refs.dateHeader;
      const content = this.$refs.scrollContainer;
      header.addEventListener('scroll', () => {
        content.scrollLeft = header.scrollLeft;
      });
      content.addEventListener('scroll', () => {
        header.scrollLeft = content.scrollLeft;
      });
    },

    // 日期格式化
    formatDate(date) {
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    },

    // 日期表头格式化
    formatDateHeader(date) {
      const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      return `${date.getMonth() + 1}/${date.getDate()} ${days[date.getDay()]}`;
    },

    // 检查是否是今天
    isToday(date) {
      const today = new Date();
      return date.getDate() === today.getDate() && 
             date.getMonth() === today.getMonth() && 
             date.getFullYear() === today.getFullYear();
    },

    // 检查是否是周末
    isWeekend(date) {
      const day = date.getDay();
      return day === 0 || day === 6;
    },

    // 获取指定单元格的过滤后订单
    getFilteredOrdersForCell(machineId, date) {
      return this.filteredOrders.filter(order => 
        order.machineId === machineId && 
        date >= order.startDate && 
        date <= order.endDate &&
        this.isSameDate(date, order.startDate)
      );
    },

    // 获取指定单元格的所有订单（用于搜索前）
    getOrdersForCell(machineId, date) {
      return this.orders.filter(order => 
        order.machineId === machineId && 
        date >= order.startDate && 
        date <= order.endDate &&
        this.isSameDate(date, order.startDate)
      );
    },

    // 获取订单块的样式
    getOrderBlockStyle(order, date) {
      const days = order.duration;
      return {
        width: `${days * this.cellWidth - 8}px`,
        backgroundColor: order.color,
        color: order.textColor
      };
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        active: '生产中',
        completed: '已完成',
        pending: '待生产'
      };
      return statusMap[status] || status;
    },

    // 检查两个日期是否相同
    isSameDate(date1, date2) {
      return date1.getDate() === date2.getDate() && 
             date1.getMonth() === date2.getMonth() && 
             date1.getFullYear() === date2.getFullYear();
    },

    // 显示订单工具提示
    showTooltip(event, order) {
      this.tooltip = {
        visible: true,
        order: {
          ...order,
          machine: this.machines.find(m => m.id === order.machineId)?.name || '未知设备'
        },
        x: event.pageX + 15,
        y: event.pageY
      };
    },

    // 隐藏工具提示
    hideTooltip() {
      this.tooltip.visible = false;
    },

    // 移动日期范围
    shiftDateRange(days) {
      this.dateHeaders = this.dateHeaders.map(date => {
        const newDate = new Date(date);
        newDate.setDate(date.getDate() + days);
        return newDate;
      });
    },

    // 返回今天
    goToToday() {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      this.dateHeaders = Array.from({ length: 61 }, (_, i) => {
        const date = new Date(today);
        date.setDate(today.getDate() - 30 + i);
        return date;
      });
      this.$refs.dateHeader.scrollLeft = 30 * this.cellWidth;
      this.$refs.scrollContainer.scrollLeft = 30 * this.cellWidth;
    }
  }
};
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  text-align: center;
}

/* 主容器布局 */
.main-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
  padding: 20px;
  gap: 20px;
  overflow: hidden;
}

/* 上下两部分布局 */
.gantt-section {
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

.unscheduled-section {
  height: 300px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 新增按钮样式 */
.today-button {
 background: #4CAF50;
 color: white;
 border: none;
 padding: 8px 12px;
 border-radius: 4px;
 cursor: pointer;
 margin-right: 10px;
 transition: background 0.3s;
 font-size: 14px;
}
.today-button:hover {
 background: #45a049;
}

/* 高亮样式 */
.date-cell.highlighted {
 background: linear-gradient(to bottom, #ffc107, #e0a800);
 font-weight: bold;
}

/* 搜索区域样式 */
.search-container {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 0 20px 10px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.search-box {
  display: flex;
  align-items: center;
  gap: 10px;
  position: relative;
  flex-grow: 1;
}

.search-box input {
  flex-grow: 1;
  padding: 10px 15px 10px 35px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s;
}

.search-box input:focus {
  border-color: #3498db;
}

.search-box i {
  position: absolute;
  left: 15px;
  color: #999;
}

.search-result {
  margin-top: 8px;
  font-size: 13px;
  color: #666;
  text-align: right;
}

.container {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.gantt-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.header-container {
  display: flex;
  background-color: #2c3e50;
  color: white;
  z-index: 10;
}

.machine-header {
  width: 150px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right: 1px solid #3a506b;
  position: sticky;
  left: 0;
  z-index: 20;
}

.date-header-container {
  flex-grow: 1;
  overflow-x: auto;
  scrollbar-width: thin;
  scrollbar-color: #3498db #2c3e50;
}

.date-header-container::-webkit-scrollbar {
  height: 8px;
}

.date-header-container::-webkit-scrollbar-track {
  background: #2c3e50;
}

.date-header-container::-webkit-scrollbar-thumb {
  background: #3498db;
  border-radius: 4px;
}

.date-header {
  display: flex;
  height: 100%;
  min-width: max-content;
}

.date-cell {
  width: 100px;
  padding: 15px 0;
  text-align: center;
  border-right: 1px solid #3a506b;
  flex-shrink: 0;
  font-weight: 500;
  background-color: #2c3e50;
  transition: background-color 0.2s;
  position: relative;
}

.date-cell.today {
  background: linear-gradient(to bottom, #e74c3c, #c0392b);
  font-weight: bold;
}

.date-cell.today::after {
  content: "今天";
  position: absolute;
  bottom: 3px;
  left: 0;
  right: 0;
  font-size: 10px;
  color: rgba(255, 255, 255, 0.9);
}

.date-cell.weekend {
  background-color: #34495e;
}

.body-container {
  display: flex;
  flex-grow: 1;
  overflow: auto;
  position: relative;
}

.machine-names {
  width: 150px;
  flex-shrink: 0;
  background-color: #f8f9fa;
  border-right: 1px solid #e0e0e0;
  position: sticky;
  left: 0;
  z-index: 15;
}

.machine-cell {
  height: 70px;
  padding: 0 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid #e0e0e0;
  font-weight: 600;
  color: #2c3e50;
  background-color: #f8f9fa;
  transition: all 0.2s;
  font-size: 1.1rem;
  position: sticky;
  left: 0;
  z-index: 10;
}

/* 拖动时的压机高亮样式 */
.machine-cell.machine-hover {
  background-color: #d1e7dd;
  border-left: 3px solid #28a745;
}

.gantt-row.row-hover {
  background-color: #f1f8e9;
}

.machine-cell:hover {
  background-color: #e9ecef;
}

.gantt-body {
  flex-grow: 1;
  min-width: max-content;
  position: relative;
}

.gantt-row {
  display: flex;
  height: 70px;
  border-bottom: 1px solid #e0e0e0;
  position: relative;
}

.gantt-cell {
  width: 100px;
  flex-shrink: 0;
  border-right: 1px solid #e0e0e0;
  position: relative;
  background-color: #ffffff;
  transition: background-color 0.2s;
}

.gantt-cell.weekend {
  background-color: #f9f9f9;
}

.gantt-cell:hover {
  background-color: #f0f8ff;
}

.order-block {
  position: absolute;
  top: 10px;
  height: 50px;
  left: 4px;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 4px;
  font-weight: 600;
  font-size: 12px;
  padding: 0 8px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  z-index: 1;
  cursor: move; /* 显示可拖动光标 */
  transition: all 0.2s;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

/* 订单信息区域 */
.order-info {
  display: flex;
  align-items: center;
  gap: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 进度条容器 */
.progress-container {
  height: 10px;
  width: 100%;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
  overflow: hidden;
}

/* 进度条 */
.progress-bar {
  height: 100%;
  transition: width 0.5s ease;
}

/* 进度文本 */
.progress-text {
  font-size: 10px;
  font-weight: bold;
  text-shadow: 0 0 2px rgba(0, 0, 0, 0.2);
}

/* 拖动中的订单样式 */
.order-block.dragging {
  opacity: 0.85;
  transform: scale(1.02);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
  z-index: 10;
  border: 2px dashed #3498db;
}

.order-block .separator {
  opacity: 0.7;
}

.order-block:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 12px rgba(0, 0, 0, 0.2);
  z-index: 3;
}

.tooltip {
  position: fixed;
  background: rgba(0, 0, 0, 0.85);
  color: white;
  padding: 12px 16px;
  border-radius: 6px;
  font-size: 14px;
  max-width: 300px;
  z-index: 100;
  pointer-events: none;
  transform: translate(10px, -50%);
  backdrop-filter: blur(4px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  line-height: 1.6;
  text-align: left;
}

.tooltip h4 {
  margin-bottom: 8px;
  color: #3498db;
  font-size: 16px;
  text-align: left;
}

.tooltip p {
  margin: 4px 0;
  text-align: left;
}

.status-indicator {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 6px;
}

.status-active {
  background-color: #2ecc71;
}

.status-completed {
  background-color: #3498db;
}

.status-pending {
  background-color: #f39c12;
}

.empty-cell {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #95a5a6;
  font-size: 12px;
  font-style: italic;
}

.today-marker {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 2px;
  background: #e74c3c;
  z-index: 2;
}

.scroll-indicator {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  z-index: 5;
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 拖拽提示 */
.drag-hint {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(52, 152, 219, 0.9);
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  z-index: 100;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
}

/* 冲突警告 */
.conflict-warning {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(231, 76, 60, 0.9);
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  z-index: 100;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
}

/* 未排产订单部分样式 */
.section-header {
  padding: 15px 20px;
  background-color: #2c3e50;
  color: white;
  border-bottom: 1px solid #3a506b;
}

.section-header h2 {
  font-size: 18px;
  font-weight: 500;
  margin: 0;
  text-align: left;
}

.table-container {
  display: flex;
  flex-direction: column;
  height: calc(100% - 53px);
  overflow: hidden;
}

/* 表格表头（冻结） */
.table-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
  flex-shrink: 0;
  position: sticky;
  top: 0;
  z-index: 10;
}

/* 表格内容（可滚动） */
.table-body {
  flex-grow: 1;
  overflow-y: auto;
}

/* 表格行和单元格样式 */
.table-row {
  display: flex;
  width: 100%;
  height: 40px; /* 缩小行高 */
  border-bottom: 1px solid #e0e0e0;
  transition: background-color 0.2s;
}

.table-row.row-hover {
  background-color: #f1f8e9;
}

.table-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 12px;
  font-size: 14px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1; /* 平均分配宽度 */
  border-right: 1px solid #e0e0e0;
}

/* 移除最后一列的右边框，避免表格最右侧出现多余边框 */
.table-cell:last-child {
  border-right: none;
}

/* 表格空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #95a5a6;
  padding: 40px 0;
  gap: 15px;
}

.empty-state i {
  font-size: 40px;
  opacity: 0.5;
}

.empty-state p {
  font-size: 14px;
}

@media (max-width: 992px) {
  .gantt-container {
    height: 100%;
  }
  
  .date-cell, .gantt-cell {
    width: 80px;
  }
  
  .machine-header, .machine-names {
    width: 120px;
  }
  
  .order-block {
    font-size: 11px;
    gap: 3px;
    padding: 0 5px;
  }
  
  /* 响应式调整表格 */
  .table-cell {
    font-size: 13px;
    padding: 0 8px;
  }
}

@media (max-width: 768px) {
  .main-container {
    padding: 10px;
    gap: 10px;
  }
  
  .container {
    width: 100%;
    height: 100%;
    margin: 0;
  }
  
  .date-cell, .gantt-cell {
    width: 70px;
    font-size: 0.85rem;
  }
  
  .machine-header, .machine-names {
    width: 100px;
  }
  
  .machine-cell {
    font-size: 1rem;
  }
  
  .order-block {
    font-size: 10px;
    gap: 2px;
    padding: 0 3px;
  }
  
  .progress-container {
    height: 4px;
  }
  
  /* 响应式调整未排产订单表格 */
  .unscheduled-section {
    height: 250px;
  }
  
  .table-cell {
    font-size: 12px;
    padding: 0 5px;
  }
}
</style>
